<?php
class GiaodichmuontrasController extends AppController {

	var $name = 'Giaodichmuontras';
	var $uses = array('Giaodichmuontra','Docgia','Hinhthucxuphat','Bienlaiphat','Chitietvipham','Nhanvien');
	var $helpers = array('Form','Html','Js','flashChart');
	var $components = array('RequestHandler','Email');

	function index() {
		$this->Giaodichmuontra->recursive = 0;
		$this->set('giaodichmuontras', $this->paginate());
	}

	function view($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid giaodichmuontra', true));
			$this->redirect(array('action' => 'index'));
		}
		$this->set('giaodichmuontra', $this->Giaodichmuontra->read(null, $id));
	}

	function add() {
		if (!empty($this->data)) {
			$this->Giaodichmuontra->create();
			if ($this->Giaodichmuontra->save($this->data)) {
				$this->Session->setFlash(__('The giaodichmuontra has been saved', true));
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('The giaodichmuontra could not be saved. Please, try again.', true));
			}
		}
		$docgias = $this->Giaodichmuontra->Docgia->find('list');
		$nhanviens = $this->Giaodichmuontra->Nhanvien->find('list');
		$cuonsaches = $this->Giaodichmuontra->Cuonsach->find('list');
		$this->set(compact('docgias', 'nhanviens', 'cuonsaches'));
	}

	function edit($id = null) {
		if (!$id && empty($this->data)) {
			$this->Session->setFlash(__('Invalid giaodichmuontra', true));
			$this->redirect(array('action' => 'index'));
		}
		if (!empty($this->data)) {
			if ($this->Giaodichmuontra->save($this->data)) {
				$this->Session->setFlash(__('The giaodichmuontra has been saved', true));
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('The giaodichmuontra could not be saved. Please, try again.', true));
			}
		}
		if (empty($this->data)) {
			$this->data = $this->Giaodichmuontra->read(null, $id);
		}
		$docgias = $this->Giaodichmuontra->Docgia->find('list');
		$nhanviens = $this->Giaodichmuontra->Nhanvien->find('list');
		$cuonsaches = $this->Giaodichmuontra->Cuonsach->find('list');
		$this->set(compact('docgias', 'nhanviens', 'cuonsaches'));
	}

	function delete($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid id for giaodichmuontra', true));
			$this->redirect(array('action'=>'index'));
		}
		if ($this->Giaodichmuontra->delete($id)) {
			$this->Session->setFlash(__('Giaodichmuontra deleted', true));
			$this->redirect(array('action'=>'index'));
		}
		$this->Session->setFlash(__('Giaodichmuontra was not deleted', true));
		$this->redirect(array('action' => 'index'));
	}

	function muonsach()
	{
		if(!empty($this->data))
		{
            $nhanvien = $this->Session->read('cur_nvid');
			$this->data['Giaodichmuontra']['nhanvien_id']=$nhanvien;
			$this->data['Giaodichmuontra']['ngaymuon']=date('Y-m-d');
			$this->data['Giaodichmuontra']['hantra']=date('Y-m-d', time()+(86400)*7);
			$this->Giaodichmuontra->create();
			if($this->Giaodichmuontra->save($this->data))
			{
				$message = 'Đã lưu';
			}
			else
			{
				$message = 'Không thể lưu';
			}
		}
		$this->Giaodichmuontra->Docgia->displayField ='tendg';
		$docgias = $this->Giaodichmuontra->Docgia->find('list');
		
		$dssachdangmuon =$this->Giaodichmuontra->find('list',array('recursive'=>-1,'fields'=>array('cuonsach_id','cuonsach_id'),'conditions'=>array('ngaytra'=>null)));
		$this->Giaodichmuontra->Cuonsach->displayField ='macs';
		$cuonsachs = $this->Giaodichmuontra->Cuonsach->find('list',array('conditions'=>array('NOT'=>array('id'=>$dssachdangmuon),'left(macs,3) !='=>'MON')));
		$this->set(compact('docgias','cuonsachs','message'));
	}

	function trasach()
	{
		/*if(!empty($this->data))
		{
			$today = date('Y-m-d');
			$this->Giaodichmuontra->id = $this->data['Giaodichmuontra']['cuonsach_id'];
			if($this->Giaodichmuontra->saveField('ngaytra',$today))
			{$this->Session->setFlash(__('Đã Lưu',true));}
			else
			{$this->Session->setFlash(__('Không thể lưu',true));}
		}*/
		$this->Hinhthucxuphat->displayField='tenhtxp';
		$htviphams= $this->Hinhthucxuphat->find('list');
		$this->Giaodichmuontra->Docgia->displayField ='tendg';
		$docgias = $this->Giaodichmuontra->Docgia->find('list');
		$masachs = $this->Giaodichmuontra->find('list',array('recursive'=>2,
													'conditions'=>array('ngaytra'=>null),'fields'=>array('Cuonsach.macs')));
		
		$this->set(compact('masachs','docgias','htviphams'));
	}

	function giahan($id=null)
	{
		if(!$id)
			$this->redirect(array('controller'=>'pages','action'=>'home'));
		$giaodich = $this->Giaodichmuontra->find('first',array('recursive'=>-1,
														'conditions'=>array('id'=>$id)));
		$hantracu = $giaodich['Giaodichmuontra']['hantra'];
		$hantramoi = date('Y-m-d', strtotime($hantracu)+(86400)*7);
		$this->Giaodichmuontra->id=$id;
		if($this->Giaodichmuontra->saveField('hantra', $hantramoi))
		{$this->Session->setFlash(__('Gia hạn thành công',true));}
		else
		{$this->Session->setFlash(__('Gia hạn không thành công',true));}
		$this->redirect(array('action'=>'sachmuon',$giaodich['Giaodichmuontra']['docgia_id']));
	}

	function sachmuon($docgia_id=null)
	{
		if(!$docgia_id)
			$this->redirect(array('controller'=>'pages','action'=>'home'));
		
		$this->Giaodichmuontra->Cuonsach->unbindModel(array('hasMany'=>array('Giaodichmuontra','Chitiethdtl')));
		$this->Giaodichmuontra->unbindModel(array('belongsTo'=>array('Nhanvien','Docgia')));
		$giaodichs = $this->Giaodichmuontra->find('all',array('recursive'=>2,'conditions'=>array('docgia_id'=>$docgia_id,'ngaytra'=>null)));
		$this->set(compact('giaodichs'));
	}
    
    function dssachmuon()
	{
		$linhvucs=$this->Giaodichmuontra->query('SELECT lv.tenlv,count(*) as tong FROM `dausaches` ds,cuonsaches cs, giaodichmuontras gd, linhvucs lv
                                                where cs.dausach_id=ds.id
                                                and gd.cuonsach_id=cs.id
                                                and lv.id=ds.linhvuc_id
                                                and gd.ngaytra is NULL
                                                group by ds.linhvuc_id');
        $ngonngus=$this->Giaodichmuontra->query('SELECT nn.tennn,count(*) as tong FROM `dausaches` ds,cuonsaches cs, giaodichmuontras gd, ngonnguks nn
                                                where cs.dausach_id=ds.id
                                                and gd.cuonsach_id=cs.id
                                                and nn.id=ds.ngonnguk_id
                                                and gd.ngaytra is NULL
                                                group by nn.id');
		$this->Giaodichmuontra->Cuonsach->unbindModel(array('hasMany'=>array('Giaodichmuontra','Chitiethdtl')));
		$this->Giaodichmuontra->unbindModel(array('belongsTo'=>array('Nhanvien','Docgia')));
		$this->paginate=array('recursive'=>2,'conditions'=>array('ngaytra'=>null));
        $giaodichs=$this->paginate();
		$this->set(compact('giaodichs','linhvucs','ngonngus'));
	}
	
	function layttdocgia()
	{
		$this->layout='ajax';
		$id = $this->data['Giaodichmuontra']['docgia_id'];
		$docgia = $this->Docgia->find('first',array('recursive'=>-1,'conditions'=>array('id'=>$id)));
		$this->set('docgia',$docgia);
	}

	function laysachdangmuon()
	{
		$this->layout='ajax';
		$docgia_id = $this->data['Giaodichmuontra']['docgia_id'];
		$sachdangmuons = $this->Giaodichmuontra->find('all',array('recursive'=>2,'conditions'=>array('docgia_id'=>$docgia_id,'ngaytra'=>null)));
		
		$this->set('sachdangmuons',$sachdangmuons);
	}

	function luumuonsach()
	{
		$this->layout='ajax';
		$docgia_id = $this->data['Giaodichmuontra']['docgia_id'];
		$dssachdangmuon =$this->Giaodichmuontra->find('list',array('recursive'=>-1,'fields'=>array('cuonsach_id','cuonsach_id'),'conditions'=>array('docgia_id'=>$docgia_id,'ngaytra'=>null)));
		 
		if(count($dssachdangmuon) <= 3)
		{
			if(!array_key_exists($this->data['Giaodichmuontra']['cuonsach_id'], $dssachdangmuon))
			{
				$nhanvien = $this->Session->read('cur_nvid');
				$this->data['Giaodichmuontra']['nhanvien_id']=$nhanvien;
				$this->data['Giaodichmuontra']['ngaymuon']=date('Y-m-d');
				$this->data['Giaodichmuontra']['hantra']=date('Y-m-d', time()+(86400)*7);
				$this->Giaodichmuontra->create();
				if($this->Giaodichmuontra->save($this->data))
				{
					$message = 'Đã lưu';
				}
				else
				{
					$message = 'Không thể lưu';
				}
			}else{$message = 'Quyển này đã được mượn';}
		}
		else{$message = 'Chỉ mượn được tối đa 4 cuốn';}
		$sachdangmuons = $this->Giaodichmuontra->find('all',array('recursive'=>2,'conditions'=>array('docgia_id'=>$docgia_id,'ngaytra'=>null)));
		$this->set(compact('sachdangmuons','message'));
	}

	function layttcuonsach()
	{
		$this->layout = 'ajax';
		$id = $this->data['Giaodichmuontra']['cuonsach_id'];
		$cuonsach = $this->Giaodichmuontra->Cuonsach->find('first',array('recursive'=>2,'conditions'=>array('Cuonsach.id'=>$id)));
		$this->set(compact('cuonsach'));
	}

	function laysachdangmuontr()
	{
		$this->layout = 'ajax';
		$docgia_id = $this->data['Giaodichmuontra']['docgia_id'];
		$sachdangmuons = $this->Giaodichmuontra->find('all',array('recursive'=>2,'conditions'=>array('docgia_id'=>$docgia_id,'ngaytra'=>null)));
		$this->set('sachdangmuons',$sachdangmuons);
	}

	function luutrasach()
	{
		$this->layout = 'ajax';
		$error =0;
		$sachmuon = $this->data['Giaodichmuontra']['check'];
		if($this->data['Giaodichmuontra']['phat']==1)
		{
			$nhanvien = $this->Session->read('cur_nvid');
			$record['Bienlaiphat']['nhanvien_id']= $nhanvien;
			$record['Bienlaiphat']['ngaylap']=date('Y-m-d');
			$this->Bienlaiphat->create();
			if($this->Bienlaiphat->saveAll($record))
			{
				$recordct['Chitietvipham']['docgia_id']=$this->data['Giaodichmuontra']['docgia_id'];
				$recordct['Chitietvipham']['bienlaiphat_id']=$this->Bienlaiphat->id;
				$recordct['Chitietvipham']['hinhthucxuphat_id']=$this->data['Giaodichmuontra']['htxp'];
				$recordct['Chitietvipham']['mucphat']=$this->data['Giaodichmuontra']['mucphat'];
				$recordct['Chitietvipham']['ghichu']=$this->data['Giaodichmuontra']['ghichu'];
				$this->Chitietvipham->create();
				if($this->Chitietvipham->saveAll($recordct))
				{
						
				}else
					;//$error = 1;
			}
			else 
				;//$error = 1;
		}
		
		foreach ($sachmuon as $gdid=>$gdvalue)
		{
			if($gdvalue==1)
			{
				$this->Giaodichmuontra->id =$gdid;
				$today = date('Y-m-d');
				if(!$this->Giaodichmuontra->saveField('ngaytra',$today))
				{
					$error = 1;
				}
			}
		}
		
		$docgia_id = $this->data['Giaodichmuontra']['docgia_id'];
		$sachdangmuons = $this->Giaodichmuontra->find('all',array('recursive'=>2,'conditions'=>array('docgia_id'=>$docgia_id,'ngaytra'=>null)));
		$this->set(compact('sachdangmuons','error'));
	}

	function lichsumtr($docgia_id=null)
	{
		if(!$docgia_id)
			$this->redirect(array('controller'=>'pages','action'=>'home'));
		
		$this->Giaodichmuontra->Cuonsach->unbindModel(array('hasMany'=>array('Giaodichmuontra','Chitiethdtl')));
		$this->Giaodichmuontra->unbindModel(array('belongsTo'=>array('Nhanvien','Docgia')));
		$giaodichs = $this->Giaodichmuontra->find('all',array('recursive'=>2,'conditions'=>array('docgia_id'=>$docgia_id,'ngaytra !='=>null)));
		$this->set(compact('giaodichs'));
	}

	function giahan_tt()
	{
		$this->Hinhthucxuphat->displayField='tenhtxp';
		$htviphams= $this->Hinhthucxuphat->find('list');
		$this->Giaodichmuontra->Docgia->displayField ='tendg';
		$docgias = $this->Giaodichmuontra->Docgia->find('list');
		$masachs = $this->Giaodichmuontra->find('list',array('recursive'=>2,
													'conditions'=>array('ngaytra'=>null),'fields'=>array('Cuonsach.macs')));
		$this->set(compact('masachs','docgias','htviphams'));
	}

	function laysachmuongh()
	{
		$this->layout = 'ajax';
		$docgia_id = $this->data['Giaodichmuontra']['docgia_id'];
		$sachdangmuons = $this->Giaodichmuontra->find('all',array('recursive'=>2,'conditions'=>array('docgia_id'=>$docgia_id,'ngaytra'=>null)));
		$this->set('sachdangmuons',$sachdangmuons);
	}

	function luugiahan()
	{
		$this->layout = 'ajax';
		$error =0;
		$sachmuon = $this->data['Giaodichmuontra']['check'];		
		foreach ($sachmuon as $gdid=>$gdvalue)
		{
			if($gdvalue==1)
			{
				$gd =$this->Giaodichmuontra->find('list',array('fields'=>array('hantra'),'conditions'=>array('id'=>$gdid)));
				$hantracu = $gd[$gdid];
				$hantramoi = date('Y-m-d', strtotime($hantracu)+(86400)*7);
				$this->Giaodichmuontra->id =$gdid;
				if(!$this->Giaodichmuontra->saveField('hantra',$hantramoi))
				{
					$error = 1;
				}
			}
		}
		
		$docgia_id = $this->data['Giaodichmuontra']['docgia_id'];
		$sachdangmuons = $this->Giaodichmuontra->find('all',array('recursive'=>2,'conditions'=>array('docgia_id'=>$docgia_id,'ngaytra'=>null)));
		$this->set(compact('sachdangmuons','error'));
	}
	
	function chart()
	{
		$hide='ngaytr';
		if(!empty($this->data))
		{
			if($this->data['Giaodichmuontra']['theo']=='ngay')
			{
				$ngaybd = date('Y-m-d',strtotime($this->data['Giaodichmuontra']['ngaybd']));
				if(empty($this->data['Giaodichmuontra']['ngaykt']))
					$ngaykt = $ngaybd ;
				else
					$ngaykt = date('Y-m-d',strtotime($this->data['Giaodichmuontra']['ngaykt']));
					$conditions = "Giaodichmuontra.ngaymuon >='".$ngaybd."' and Giaodichmuontra.ngaymuon <='".$ngaykt."'";
				$hide = 'namtr';
			}
			else
			{
				$nam = date('Y',strtotime($this->data['Giaodichmuontra']['nam']));
				$conditions = "YEAR(Giaodichmuontra.ngaymuon) ='".$nam."'";
				$hide = 'ngaytr';
			}
			$querystr ="select Linhvuc.tenlv,count(Giaodichmuontra.cuonsach_id) as soluong
						from (((giaodichmuontras  Giaodichmuontra INNER JOIN cuonsaches Cuonsach on Giaodichmuontra.cuonsach_id=Cuonsach.id) INNER JOIN dausaches Dausach on Cuonsach.dausach_id=Dausach.id) RIGHT JOIN linhvucs Linhvuc on Dausach.linhvuc_id=Linhvuc.id)
						where ".$conditions."
						group by Linhvuc.id";
			$result = $this->Giaodichmuontra->query($querystr);
			$this->set(compact('result'));
		}
		else
		{		
			$querystr ="select Linhvuc.tenlv,count(Giaodichmuontra.cuonsach_id) as soluong
						from (((giaodichmuontras  Giaodichmuontra INNER JOIN cuonsaches Cuonsach on Giaodichmuontra.cuonsach_id=Cuonsach.id) INNER JOIN dausaches Dausach on Cuonsach.dausach_id=Dausach.id) RIGHT JOIN linhvucs Linhvuc on Dausach.linhvuc_id=Linhvuc.id)
						where YEAR(Giaodichmuontra.ngaymuon)='".date('Y')."'
						group by Linhvuc.id";
			$result = $this->Giaodichmuontra->query($querystr);
			$this->set(compact('result'));
		}
		$this->set(compact('hide'));
	}
	
	function dsquahan()
	{
		$failed = array();
		$isAjax = 0;
		if($this->RequestHandler->isAjax())
		{
			$isAjax = 1;
			$sachdangmuons = $this->Giaodichmuontra->find('list',array('recursive'=>-1,'conditions'=>array('ngaytra'=>null,'hantra <'=>date('Y-m-d')),'order'=>array('hantra ASC')));
			foreach ($sachdangmuons as $idgiadich)
			{
				$failed[] = $this->_guiMail($idgiadich);
			}
		}
		$this->Docgia->unbindModel(array('hasMany'=>array('Chitietvipham','Dangkydv','Giaodichmuontra'),'belongsTo'=>array('Loaidocgia')));
		$this->Giaodichmuontra->Cuonsach->unbindModel(array('hasMany'=>array('Chitiethdtl','Giaodichmuontra')));
		$this->Giaodichmuontra->unbindModel(array('belongsTo'=>array('Nhanvien')));
		$sachdangmuons = $this->Giaodichmuontra->find('all',array('recursive'=>2,'conditions'=>array('ngaytra'=>null,'hantra <'=>date('Y-m-d')),'order'=>array('hantra ASC')));
		$this->set(compact('sachdangmuons','isAjax','failed'));
	}
	
	function _guiMail($id)
	{
		$err =0;
		$this->Email->reset();
	    $giaodich = $this->Giaodichmuontra->find('first',array('recursive'=>2,'conditions'=>array('Giaodichmuontra.id'=>$id)));
	    $this->Email->to =$giaodich['Docgia']['email'];
	    $this->Email->subject = 'Cảnh báo';
	    $this->Email->from = 'Thư viện khoa CNTT - Trường Đại học cần thơ <app@example.com>';
	    $this->Email->template = 'trehan';
	    $this->Email->delivery = 'debug';
	    $this->Email->sendAs = 'text';
	    $this->set('giaodich', $giaodich);
	    if(!$this->Email->send())
	    {
	    	$err = 1;
	    }
	    if($err==1)
	    {
	    	return $id;
	    }
	    return 'true';
 }
	
}

function color()
{
	mt_srand((double)microtime()*1000000);
	$c = '';
	while(strlen($c)<6)
	{
		$c .= sprintf("%02X", mt_rand(0, 255));
	}
	return  $c;
}